# -*- coding: utf-8 -*-

from odoo import models, fields, api, modules
import logging
import requests
import json
import random
from odoo import time
import datetime

cert = ("/odoo/apps/wanlong/wliot/static/cert/client.crt",
        "/odoo/apps/wanlong/wliot/static/cert/client.key")
_logger = logging.getLogger(__name__)


class IrCron(models.Model):
    _inherit = 'ir.cron'

    @api.model
    def test_lcj(self):
        self.env["phone.verify.wizard"].send_verify_code('18271913797')

    @api.model
    def calibrate_time(self):
        ''' 时间校准 '''
        app_id = self.env['ir.config_parameter'].get_param('iot_app_id')
        secret = self.env['ir.config_parameter'].get_param('iot_secret')
        version = self.env['ir.config_parameter'].get_param('version')
        params = {
            'appId': app_id,
            'secret': secret
        }
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
        response = requests.post(url="https://180.101.147.89:8743/iocm/app/sec/v1.1.0/login", data=params, cert=cert,
                                 verify=False, headers=headers)
        response = json.loads(response.text)
        access_token = response.get('accessToken')

        params = {
            'appId': app_id,
            'timeout': 0,
            'taskName': 'calibrateTime',
            'taskType': 'DeviceCmd',
            'param': {
                'type': 'DeviceType',
                'manufaturerId': 'Wanlong',
                'command': {
                    'serviceId': 'Time',
                    'method': 'CALIBRATE_TIME',
                    'paras': {
                        'timeValue': self.get_string_time(self.get_beijing_datetime(int(round((time.time()) * 1000)))),
                        'modelNum': '0000000000000000',
                        'time': self.get_string_time(self.get_beijing_datetime(int(round((time.time()) * 1000)))),
                        'codeID': random.randint(0, 16777215),
                        'cmdCode': 'timeReq',
                        'version': version
                    }
                }
            }
        }
        headers = {
            'app_key': app_id,
            'Authorization': 'Bearer %s' % access_token,
            'Content-Type': 'application/json'
        }
        response = requests.post(url="https://180.101.147.89:8743/iocm/app/batchtask/v1.1.0/tasks",
                                 data=json.dumps(params), cert=cert, verify=False, headers=headers)
        response = json.loads(response.text)
        _logger.info(response)

    @api.model
    def query_message(self):
        ''' 添加传感器更换消息 '''
        today = datetime.date.fromtimestamp(time.time())
        today = (datetime.datetime(today.year, today.month, today.day) + datetime.timedelta(days=10)).date()
        sensors = self.env['wliot.ppm.sensor'].sudo().search([
            ('deadline_date', '=', today)
        ])
        if sensors:
            for sensor in sensors:
                device = sensor.env['wliot.device'].sudo().search([
                    ('ppm_sensor_id', '=', sensor.id)
                ])
                subject = 'expire'
                subtype = "wliot.mt_iot_sensor_expire"
                partner = self.env['res.partner'].sudo().search([
                    ('id', '=', device.partner_id.id)
                ])
                partner_ids = partner.get_child()
                sensor.send_message(subject, subtype, partner_ids)

                # subtype = self.env['mail.message.subtype'].sudo().search([
                #     ('name', '=', 'expire')
                # ])
                # mail_message = self.env['mail.message'].sudo().search([
                #     ('model', '=', 'wliot.ppm.sensor'),
                #     ('res_id', '=', sensor.id),
                #     ('subtype_id', '=', subtype.id)
                # ])
                # if not mail_message:
                #     subject = 'expire'
                #     subtype = "wliot.mt_iot_sensor_expire"
                #     partner = self.env['res.partner'].sudo().search([
                #         ('id', '=', device.partner_id.id)
                #     ])
                #     partner_ids = partner.get_child()
                #     sensor.send_message(subject, subtype, partner_ids)

    @api.model
    def check_lostin(self):
        default_lostin_time_delta = self.env['ir.config_parameter'].get_param('default_lostin_time_delta')
        default_lostin_time_delta = int(default_lostin_time_delta)
        now_time = datetime.datetime.now()
        sql = "select a.update_time,a.id from wliot_device_indicator_value a group by device,a.update_time,a.id order by update_time desc limit 1 "
        self.env.cr.execute(sql)
        dicts = self.env.cr.dictfetchall()
        # device_indicator_values = self.env['wliot.device.indicator.value'].sudo().search([], order='update_time desc', limit=1)
        if dicts:
            for dict in dicts:
                device_indicator_value = self.env['wliot.device.indicator.value'].sudo().search([
                    ('id', '=', dict.get('id'))
                ], limit=1)
                update_time = datetime.datetime.strptime(device_indicator_value.update_time, "%Y-%m-%d %H:%M:%S")
                device = self.env['wliot.device'].sudo().search([
                    ('id', '=', device_indicator_value.device.id)
                ])
                time_delta = (now_time - update_time).seconds / 60
                time_delta = int(time_delta)
                _logger.info(time_delta)
                _logger.info(default_lostin_time_delta)
                if time_delta > default_lostin_time_delta:
                    # 修改设备失联状态
                    device.write({
                        'running_status': 'lostin',
                        'lostin': True
                    })
                    # 创建失联消息
                    subject = 'lostin'
                    subtype = "wliot.mt_iot_lostin"
                    partner = self.env['res.partner'].sudo().search([
                        ('id', '=', device.partner_id.id)
                    ])
                    partner_ids = partner.get_child()
                    device.send_message(subject, subtype, partner_ids)
                else:
                    if device.lostin:
                        # 修改设备失联状态
                        device.write({
                            'running_status': 'normal',
                            'lostin': False
                        })
                        # 创建失联解除消息
                        subject = 'lostin_remove'
                        subtype = "wliot.mt_iot_lostin_remove"
                        partner = self.env['res.partner'].sudo().search([
                            ('id', '=', device.partner_id.id)
                        ])
                        partner_ids = partner.get_child()
                        device.send_message(subject, subtype, partner_ids)

    def get_beijing_datetime(self, uploadtime):
        return (datetime.datetime.strptime(time.strftime('%Y-%m-%d %H:%M:%S',
                                                         time.localtime(int((long(uploadtime)) * (
                                                                 10 ** (10 - len(str(uploadtime))))))),
                                           '%Y-%m-%d %H:%M:%S') + datetime.timedelta(hours=8)).strftime(
            '%Y-%m-%d %H:%M:%S')

    def get_string_time(self, bjtime):
        bjtime = str(bjtime)
        year = bjtime[2:4]
        month = bjtime[5:7]
        day = bjtime[9:11]
        hour = bjtime[13:15]
        minute = bjtime[17:19]
        second = bjtime[21:23]
        s = '%s%s%s%s%s%s' % (year, month, day, hour, minute, second)
        _logger.info(s)
